<script setup>
import { ref, onMounted, watch } from 'vue'
import { useCollectStore } from '@/stores'
import DishItem from '@/components/DishItem.vue'

const collectStore = useCollectStore()

const manageMode = ref(false)
const isLoading = ref(false)

const toggleManage = () => {
  if (collectStore.collectDishList.length === 0) {
    uni.showToast({ title: '暂无收藏菜品', icon: 'none' })
    return
  }
  manageMode.value = !manageMode.value
  if (!manageMode.value) {
    collectStore.clearSelection()
  }
}

// 修复删除操作的结果判断
const deleteSelected = async () => {
  if (collectStore.selectedCount === 0) {
    uni.showToast({ title: '请先选择要删除的菜品', icon: 'none' })
    return
  }

  try {
    const res = await uni.showModal({
      title: '删除确认',
      content: `确定要删除选中的 ${collectStore.selectedCount} 个菜品吗？`,
      confirmText: '删除',
      cancelText: '取消'
    })
    
    if (res.confirm) {
      isLoading.value = true
      // 关键修复：准确判断删除结果
      const deleteSuccess = await collectStore.deleteCollectDish(collectStore.selectedIds)
      
      // 无论成功失败都关闭加载
      isLoading.value = false
      
      if (deleteSuccess) {
        uni.showToast({ title: '删除成功！', icon: 'success' })
        if (collectStore.collectDishList.length === 0) {
          manageMode.value = false
        }
      } else {
        // 只有确认失败时才显示错误
        uni.showToast({ title: '删除失败', icon: 'error' })
      }
    }
  } catch (err) {
    console.error('弹窗操作出错:', err)
    isLoading.value = false
    uni.showToast({ title: '操作失败', icon: 'error' })
  }
}

// 监听列表变化，强制清除无效选择（关键修复）
watch(
  () => collectStore.collectDishList,
  (newList) => {
    const validIds = newList.map(dish => dish.id)
    // 过滤掉已删除菜品的选择状态
    collectStore.selectedIds = collectStore.selectedIds.filter(
      id => validIds.includes(id)
    )
  },
  { deep: true }
)

const getCollectDishList = async () => {
  isLoading.value = true
  try {
    await collectStore.updateCollectDishList()
  } finally {
    isLoading.value = false
  }
}

watch(
  () => collectStore.collectDishList.length,
  (newLength) => {
    if (newLength === 0 && manageMode.value) {
      manageMode.value = false
    }
  }
)

onMounted(() => {
  getCollectDishList()
})
</script>

<template>
  <view class="collect-container">
    <view class="collect-header">
      <text class="collect-title">
        <text class="iconfont icon-caipin-"></text>
        收藏菜品
      </text>
      <text class="collect-count">
        共有 <text class="count-number">{{ collectStore.collectDishList.length }}</text> 个菜品
      </text>
      <view class="manage-btn" @tap="toggleManage">
        <text class="manage-btn-text">{{ manageMode ? '完成' : '管理' }}</text>
      </view>
    </view>
    
    <view class="collect-list-card">
      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 管理工具栏 -->
      <view 
        v-if="manageMode && collectStore.collectDishList.length > 0" 
        class="manage-bar"
      >
        <view class="select-all" @tap="collectStore.toggleSelectAll">
          <checkbox :checked="collectStore.isAllSelected" color="#667eea" />
          <text class="select-all-text">全选</text>
        </view>
        <view 
          class="delete-btn"
          :class="{ disabled: collectStore.selectedCount === 0 }"
          @tap="deleteSelected"
          :disabled="collectStore.selectedCount === 0"
        >
          <text class="delete-btn-text">删除所选 ({{ collectStore.selectedCount }})</text>
        </view>
      </view>
      
      <!-- 菜品列表：无论是否管理模式，只要非加载状态就显示 -->
      <view class="collect-list-horizontal" v-if="!isLoading">
        <!-- 有数据时显示列表 -->
        <view 
          v-if="collectStore.collectDishList.length > 0"
          class="dish-list-wrapper"
        >
          <view
            v-for="dish in collectStore.collectDishList"
            :key="dish.id"
            class="collect-list-item-horizontal"
          >
            <!-- 复选框：仅管理模式显示 -->
            <view class="select-checkbox" v-if="manageMode">
              <checkbox 
                :checked="collectStore.selectedIds.includes(dish.id)"
                color="#667eea"
                @tap.stop="collectStore.toggleSelect(dish.id)"
              />
            </view>
            <!-- 菜品项 -->
            <view class="dish-item-container">
              <DishItem :dish="dish" />
            </view>
          </view>
        </view>
        
        <!-- 空状态：无数据时显示 -->
        <view v-else class="empty-tip">
          <image
            src="/static/images/random-default.png"
            class="empty-img"
            mode="aspectFit"
          />
          <text class="empty-text">暂无收藏，快去发现美食吧！</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.collect-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40rpx 32rpx calc(80rpx + env(safe-area-inset-bottom)) 32rpx;
  overflow-y: auto;
}

.collect-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 40rpx;
  padding: 60rpx 40rpx 36rpx 40rpx;
  text-align: center;
  margin-bottom: 40rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  .collect-title {
    font-size: 48rpx;
    font-weight: 600;
    margin: 0 0 16rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(45deg, #667eea, #764ba2);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;

    .iconfont {
      font-size: 52rpx;
      color: #667eea;
      margin-right: 20rpx;
      -webkit-text-fill-color: initial;
    }
  }
  
  .collect-count {
    color: #666;
    font-size: 30rpx;
    margin: 0;
    display: block;
    
    .count-number {
      color: #667eea;
      font-weight: 600;
      font-size: 36rpx;
    }
  }
}

.collect-list-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 36rpx;
  padding: 48rpx 36rpx;
  box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  min-height: 440rpx;
  position: relative;
}

// 加载状态样式
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  
  .loading-text {
    font-size: 32rpx;
    color: #667eea;
  }
}

// 横向卡片列表 - 修复对齐问题
.collect-list-horizontal {
  display: flex;
  flex-direction: column;
  gap: 36rpx;
  padding: 0;
  margin: 0;
  width: 100%;

  .dish-list-wrapper {
    width: 100%;
  }
}

.collect-list-item-horizontal {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  gap: 24rpx;
  padding: 24rpx 0;
  min-height: 200rpx;
  border-bottom: 2rpx solid rgba(102, 126, 234, 0.1);
  position: relative;
  
  &:last-child {
    border-bottom: none;
  }
}

// 复选框容器 - 固定宽度确保对齐
.select-checkbox {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0; // 固定宽度，不被压缩
  padding-top: 10rpx;
  
  checkbox {
    width: 36rpx;
    height: 36rpx;
  }
}

// 菜品项容器 - 占据剩余空间，确保右侧对齐
.dish-item-container {
  flex: 1; /* 占据剩余空间 */
  min-width: 0; /* 允许内容收缩 */
}

.manage-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx;
  padding: 24rpx;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 24rpx;

  .select-all {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .select-all-text {
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  .delete-btn {
    background: linear-gradient(45deg, #ff6b6b, #ff5252);
    color: white;
    border-radius: 24rpx;
    padding: 12rpx 32rpx;
    transition: all 0.3s ease;
    cursor: pointer;
    
    &.disabled {
      background: #ccc;
      opacity: 0.6;
      cursor: not-allowed;
    }
    
    .delete-btn-text {
      font-size: 28rpx;
      font-weight: 600;
    }
  }
}

.manage-btn {
  position: absolute;
  right: 48rpx;
  top: 64rpx;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border-radius: 24rpx;
  padding: 12rpx 36rpx;
  z-index: 2;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.08);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2rpx);
  }
  
  .manage-btn-text {
    color: #fff;
    font-size: 28rpx;
    font-weight: 600;
  }
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 80rpx 0 40rpx 0;
  color: #999;
  font-size: 32rpx;
  
  .empty-img {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 24rpx;
    opacity: 0.7;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #999;
  }
}

/* 小程序样式适配 */
/* #ifdef MP-WEIXIN */
.collect-header {
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: none !important;
  border: 2rpx solid #f0f0f0 !important;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.08) !important;
  
  .collect-title {
    color: #667eea !important;
    background: none !important;
    background-clip: unset !important;
    -webkit-background-clip: unset !important;
    -webkit-text-fill-color: unset !important;
  }
}

.collect-list-card {
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: none !important;
  box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.08) !important;
}
/* #endif */

// 平板适配
@media (min-width: 768px) {
  .collect-container {
    max-width: 1600rpx;
    margin: 0 auto;
    padding-bottom: 80rpx;
  }
  
  .collect-header {
    padding: 80rpx 60rpx 48rpx 60rpx;
    
    .collect-title {
      font-size: 56rpx;
    }
  }
  
  .collect-list-card {
    padding: 64rpx 48rpx;
  }
}
</style>
